<template>
  <!-- 路径 -->
  <el-breadcrumb>
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="item in levelList" :key="item">
        {{ item }}
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import menus from "@/router/menu";
export default {
  data() {
    return {
      levelList: []
    };
  },
  watch: {
    $route: {
      immediate: true,
      handler(val) {
        if (val.meta && val.meta.path) {
          const path = JSON.parse(JSON.stringify(val.meta.path));
          this.levelList = [];
          path.forEach(item => {
            if (item.includes("menu-")) {
              const name = item.split("menu-")[1];
              const parentMenus = [];
              this.getMenuPathByName(menus, name, parentMenus);
              const titlePathArr = [];
              parentMenus
                .reverse()
                .forEach(item => titlePathArr.push(item.title));
              this.levelList.push(...titlePathArr);
            } else {
              this.levelList.push(item);
            }
          });
        } else {
          this.levelList = [];
        }
      }
    }
  },
  methods: {
    // 通过 name 获取当前 menu 的路径关系
    getMenuPathByName(menus, name, parentMenus) {
      let keepOn = true;
      menus.forEach(item => {
        if (item.name === name) {
          parentMenus.push(item);
          keepOn = false;
        }
        if (item.children && item.children.length && keepOn) {
          this.getMenuPathByName(item.children, name, parentMenus);
          if (parentMenus.some(it => item.children.includes(it))) {
            parentMenus.push(item);
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/* breadcrumb transition */
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.3s;
}

.breadcrumb-enter,
.breadcrumb-leave-active {
  opacity: 0;
  transform: translateX(20px);
}

.breadcrumb-move {
  transition: all 0.3s;
}

.breadcrumb-leave-active {
  position: absolute;
}
</style>
